package com.leo.lime.music.view;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.leo.lime.music.R;

import java.util.List;

public class LimeTextSwitcher extends TextSwitcher implements ViewSwitcher.ViewFactory {
    private static final String TAG = "LimeTextSwitcher";

    private Context mContext;
    private long mChangedDivider;
    private String mCurrentText = "";
    private List<String> mShowTexts;

    public LimeTextSwitcher(Context ctx) {
        this(ctx, null);
    }

    public LimeTextSwitcher(Context ctx, AttributeSet as) {
        super(ctx, as);

        init(ctx);
    }

    private void init(Context ctx) {
        mContext = ctx;
        mChangedDivider = ctx.getResources().getInteger(R.integer.auto_scroll_text_switcher_divider);

        setFactory(this);
        setInAnimation(getShowAnimation());
        setOutAnimation(getDismissAnimation());

        next();
    }

    public void setTextArray(List<String> strList) {
        mShowTexts = strList;
    }

    private AnimationSet getShowAnimation() {
        AnimationSet as = new AnimationSet(true);
        AlphaAnimation animation = new AlphaAnimation(0, 1);
        animation.setDuration(mChangedDivider);
        as.addAnimation(animation);
        return as;
    }

    private AnimationSet getDismissAnimation() {
        AnimationSet as = new AnimationSet(true);
        AlphaAnimation animation = new AlphaAnimation(0, 1);
        animation.setDuration(mChangedDivider);
        as.addAnimation(animation);
        return as;
    }

    public View makeView() {
        TextView tv = new TextView(mContext);
        tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        tv.setGravity(Gravity.CENTER_VERTICAL);
        tv.setSingleLine();
        tv.setTextSize(20);
        tv.setTextColor(Color.GRAY);
        return tv;
    }

    public void next() {
        if(mShowTexts != null && mShowTexts.size() > 0) {
            if(TextUtils.isEmpty(mCurrentText)) {
                mCurrentText = mShowTexts.get(0);
            } else {
                for(int i = 0; i < mShowTexts.size(); i++) {
                    if(mCurrentText.equals(mShowTexts.get(i))) {
                        if(i == mShowTexts.size() - 1) {
                            mCurrentText = mShowTexts.get(0);
                        } else {
                            mCurrentText = mShowTexts.get(i + 1);
                        }
                        break;
                    }
                }
            }
        }
        setText(mCurrentText);
    }

}
